# -*- encoding: utf-8 -*-

"""
@File:      tc_libtdb_libtdb_func_006.py.py
@Time:      2024/04/18 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libtdb_libtdb_func_006.py.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libtdb libtdb-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >ltdb_test6.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <tdb.h>
#include <fcntl.h>
#include <string.h>

#define NUM_PROCESSES 10

// 向TDB数据库中添加一个键值对的函数
void insert_into_tdb(TDB_CONTEXT *tdb, const char *key, const char *value) {
    TDB_DATA tdb_key, tdb_value;
    tdb_key.dptr = (unsigned char *)key;
    tdb_key.dsize = strlen(key) + 1;
    tdb_value.dptr = (unsigned char *)value;
    tdb_value.dsize = strlen(value) + 1;
    
    if (tdb_store(tdb, tdb_key, tdb_value, TDB_REPLACE) != 0) {
        fprintf(stderr, "无法插入键值对：%s=%s\\n", key, value);
    } else {
        printf("成功插入：%s=%s\\n", key, value);
    }
}

int main() {
    TDB_CONTEXT *tdb;
    pid_t pids[NUM_PROCESSES];
    int i;

    // 打开或创建TDB数据库
    tdb = tdb_open("ltdb_test6.tdb", 0, TDB_DEFAULT, O_CREAT | O_RDWR, 0600);
    if (!tdb) {
        fprintf(stderr, "无法打开数据库\\n");
        exit(EXIT_FAILURE);
    }

    // 创建多个子进程并写入不同的键值对
    for (i = 0; i < NUM_PROCESSES; ++i) {
        pids[i] = fork();
        if (pids[i] == 0) { // 子进程
            char key[128];
            char value[128];
            // 为每个子进程生成唯一的键值对
            snprintf(key, sizeof(key), "key_%d", i);
            snprintf(value, sizeof(value), "value_%d", getpid()); // 使用进程ID来保证值的唯一性
            // 向数据库中添加键值对
            insert_into_tdb(tdb, key, value);
            tdb_close(tdb);
            exit(EXIT_SUCCESS);
        } else if (pids[i] < 0) {
            fprintf(stderr, "创建子进程失败\\n");
            exit(EXIT_FAILURE);
        }
    }

    // 父进程等待所有子进程完成
    for (i = 0; i < NUM_PROCESSES; ++i) {
        waitpid(pids[i], NULL, 0);
    }

    // 所有子进程完成后关闭TDB数据库
    tdb_close(tdb);
    
    printf("所有插入操作完成。\\n");

    return 0;
}
EOF'''
        self.cmd(cmdline)


    def test(self):
        self.cmd("gcc -o ltdb_test6 ltdb_test6.c -ltdb")
        code, ltdb_result = self.cmd("./ltdb_test6")
        self.assertIn('所有插入操作完成', ltdb_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf ltdb_test6.c ltdb_test6 ltdb_test6.tdb")
